<template>
  <div>
    <bread :second="'商品管理'" :third="'参数列表'"></bread>
    <!-- 表单 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
      <!-- 下拉菜单 -->
      <el-form ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="选择商品分类:" style="text-align: left;margin:20px 0;">
          <el-cascader
            v-model="value"
            :options="catelist"
            clearable
            :props="options"
            expandTrigger="hover"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <!-- tab栏切换 -->
      <el-tabs v-model="activeName" @tab-click="handleClick" style="text-align:left;">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="disabled"
            size="small"
            style="margin-bottom:10px;"
            @click="dialogFormVisibleAddCate=true"
          >添加参数</el-button>
          <!-- 表格1 -->
          <el-table :data="manyData" border style="width: 100%">
            <el-table-column type="expand" width="50">
              <!-- 插槽 -->
              <template slot-scope="scope">
                  <el-tag 
                  style="margin:5px"
                  v-for="(item,index) in scope.row.attr_vals" :key ='index'
                  closable
                   @close="handleClose(index,scope.row)"
                  >
                  {{item}}
                  </el-tag>
                <el-input
                style="width:70px"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
              
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
                <!-- <pre>{{scope.row}}</pre> -->
              </template>

            </el-table-column>
            <el-table-column type="index" label="#" width="50"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="280"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary"  :disabled="disabled"  @click="AttrManys(scope.row)">
                  <i class="el-icon-edit"></i>编辑
                </el-button>
                <el-button size="mini" type="danger"  :disabled="disabled" @click="HeadlerDelCate(scope.row)">
                  <i class="el-icon-delete"></i>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="small"
            :disabled="disabled"
            style="margin-bottom:10px;"
            @click="dialogFormVisibleStatic=true"
          >添加属性</el-button>
          <!-- 表格2 -->
          <el-table :data="onlyData" border style="width: 100%">
            <el-table-column type="expand" width="50">
              <!-- 插槽 -->
            <template slot-scope="scope">
                  <el-tag 
                  style="margin:5px"
                  v-for="(item,index) in scope.row.attr_vals" :key ='index'
                  closable
                   @close="handleClose(index,scope.row)"
                  >
                  {{item}}
                  </el-tag>
                <el-input
                  class="input-new-tag"
                  style="width:70px"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
              
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
                <!-- <pre>{{scope.row}}</pre> -->
              </template>


            </el-table-column>

            <el-table-column type="index" label="#" width="50"></el-table-column>

            <el-table-column prop="attr_name" label="属性名称" width="280"></el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" :disabled="disabled" @click="AttrManys(scope.row)">
                  <i class="el-icon-edit"></i>编辑
                </el-button>
                <el-button size="mini" type="danger" :disabled="disabled" @click="HeadlerDelCate(scope.row)">
                  <i class="el-icon-delete"></i>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数 弹出层 -->

    <el-dialog title="添加参数" :visible.sync="dialogFormVisibleAddCate">
      <el-form :model="formAddCat" :rules='rules' ref="formAddCat">
        <el-form-item label="动态参数：" :label-width="formLabelWidth" prop="attr_name">
          <el-input v-model="formAddCat.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAddCate = false">取 消</el-button>
        <el-button type="primary" @click="CatAddButton">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 静态参数 -->
        <el-dialog title="添加参数" :visible.sync="dialogFormVisibleStatic">
      <el-form :model=" formAddCatStatic" :rules='rules' ref="formAddCatStatic">
        <el-form-item label="动态参数：" :label-width="formLabelWidth" prop="attr_name">
          <el-input v-model="formAddCatStatic.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleStatic = false">取 消</el-button>
        <el-button type="primary" @click="CatAddStatic">确 定</el-button>
      </div>
    </el-dialog>


    <!--动态参数编辑 -->
      <el-dialog title="编辑动态参数" :visible.sync="dialogFormVisibleMany">
      <el-form :model=" formAddCatStaticMany" :rules='rules' ref="formAddCatStaticMany">
        <el-form-item label="动态参数：" :label-width="formLabelWidth" prop="attr_name">
          <el-input v-model="formAddCatStaticMany.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleMany = false">取 消</el-button>
        <el-button type="primary" @click="CatAddStaticManys">确 定</el-button>
      </div>
    </el-dialog>

        <!--静态参数编辑 -->
      <el-dialog title="编辑静态参数" :visible.sync="dialogFormVisibleMany">
      <el-form :model=" formAddCatStaticMany" :rules='rules' ref="formAddCatStaticMany">
        <el-form-item label="静态参数：" :label-width="formLabelWidth" prop="attr_name">
          <el-input v-model="formAddCatStaticMany.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleMany = false">取 消</el-button>
        <el-button type="primary" @click="CatAddStaticManys">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  categoriesList_api,
  cateParamsList_api,
  DeleteCateList_api,
   AddCatsList_api,
    AddAttrList_api,
    deleteAttrList_api
   
} from "@/api/index.js";
export default {
  data() {
    return {
      formAddCat: {
        attr_name: "",
        id:'',
        attr_sel:'',
        attr_vals:''
      },
     formAddCatStatic: {
        attr_name: "",
        id:'',
        attr_sel:'',
        attr_vals:''
      },
      // 编辑
      formAddCatStaticMany:{
        attr_name: "",
        attrId:'',
        attr_sel:'',
        id:''
      },
      // 弹出层表单验证
      rules: {
        attr_name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
      },
      formLabelWidth: "120px",
      dialogFormVisibleAddCate: false,
      dialogFormVisibleStatic:false,
      dialogFormVisibleMany:false,
      inputVisible: false,
      inputValue: "",
      // tab栏切换
      activeName: "many",
      params: { type: 3 },
      disabled: true,
      value: "",
      // tag标签
      attrDataList:[],

      // 商品分类列表
      catelist: [],
      options: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 表格数据
      manyData: [],
      // 表格数据
      onlyData: [],
    };
  },
  created() {
    this.getGoodsFl();
  },
  computed: {
    catId(){
      if(this.value.length == 3){
        return  this.value[2]
      }else{
        return null
      }
    }
  },
  methods: {
    async handleChange() {
      if(this.value.length!=3) {
        this.value=[]
      }

      if (this.value.length == 3) {
        this.disabled = false;
        // 发送请求
        this.paramsfn();
      } else {
        this.disabled = true;
      }
    },
    async paramsfn() {
      var id = this.value[this.value.length - 1];
     
      var sel = this.activeName;
      const { data: res } = await cateParamsList_api({ id, sel });

      // 遍历数据，添加inputVisible: false属性
      // res.data.inputVisible = false;
      // res.data.inputValue = ''
      res.data.forEach(item=>{
        item.inputVisible = false
        item.inputValue = ''
        item.attr_vals=item.attr_vals.split(',').filter(item=>item.length!=0)
      })

      if (this.activeName == "many") {
        this.manyData = res.data;
      } else {
        this.onlyData = res.data;
      }
    },
    // 添加分类
    CatAddButton() {
            // 二次验证
      this.$refs.formAddCat.validate(async valid=>{
        if(!valid) return
        this.dialogFormVisibleAddCate= false;
        this.formAddCat.id=this.value[this.value.length - 1]
        this.formAddCat.attr_sel=this.activeName
        // console.log(this.formAddCat);
        const {data:res} = await  AddCatsList_api(this.formAddCat)
        // console.log(res,7777);
             this.$message({
            type: "success",
            message: res.meta.msg,
          });
        // 发送请求刷新列表
        this.paramsfn();
        // 清空表单
         this.$refs.formAddCat.resetFields();
      })
    },
    // 静态参数添加
    CatAddStatic(){
            // 二次验证
      this.$refs.formAddCatStatic.validate(async valid=>{
        if(!valid) return
        this.dialogFormVisibleStatic= false;
        this.formAddCatStatic.id=this.value[this.value.length - 1]
        this.formAddCatStatic.attr_sel=this.activeName
        // console.log(this.formAddCat);
        const {data:res} = await  AddCatsList_api(this.formAddCatStatic)
        // console.log(res,7777);
             this.$message({
            type: "success",
            message: res.meta.msg,
          });
        // 发送请求刷新列表
        this.paramsfn();
                // 清空表单
         this.$refs.formAddCatStatic.resetFields();
      })
    },

    // // tab 栏切换
    handleClick(tab, event) {
      // console.log(tab, event);
      // 发送请求
      this.paramsfn();
    },
    // 点击删除按钮
    async HeadlerDelCate(row) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
      if (result == "confirm") {
        //   发送请求
        const { data: res } = await DeleteCateList_api({
          id: row.cat_id,
          attrid: row.attr_id,
        });
        // console.log(res, 333);

        this.$message({
          type: "success",
          message: res.meta.msg,
        });
        // 刷新列表
        this.paramsfn();
      }
    },
    // 动态参数编辑
    AttrManys(row){

      this.dialogFormVisibleMany=true
      this.formAddCatStaticMany.attr_name=row.attr_name
      this.formAddCatStaticMany.id = this.catId
      this.formAddCatStaticMany.attrId = row.attr_id
      this.formAddCatStaticMany.attr_sel = this.activeName
      // console.log(row,9070); 
    },
    // 动态参数编辑确定按钮
  async CatAddStaticManys(){
           // 二次验证
      this.$refs.formAddCatStaticMany.validate(async valid=>{
        if(!valid) return
        this.dialogFormVisibleMany=false
        const {data:res} =await AddAttrList_api(this.formAddCatStaticMany)
             this.$message({
            type: "success",
            message: res.meta.msg,
          });
        // 发送请求刷新列表
        this.paramsfn();
                // 清空表单
         this.$refs.formAddCatStaticMany.resetFields();
      })
    
    
    
     

    },

    async getGoodsFl() {
      const { data: res } = await categoriesList_api(this.params);
      // 商品分类列表
      this.catelist = res.data;
    },
    // 删除参数
   async handleClose(index,row) {
      // var params={
      //   id:this.catId,
      //   attrid:row.attr_id
      // }
     
      // const {data:res} = await deleteAttrList_api(params)
      // // console.log(res);
       row.attr_vals.splice(index,1) 
      // // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        //   this.$message({
        //   showClose: true,
        //   message:,
        //   type: 'success'
        // });
         this.GetAttrList(row)
       
    },

    showInput(row) {
      row.inputVisible = !row.inputVisible;
      // this.inputVisible = true;
      // $nextTick 等页面重新渲染完成后再执行
        this.$nextTick( _ => {

          this.$refs.saveTagInput.$refs.input.focus();
        });

    },
    // 失去焦点
    handleInputConfirm(row) {
      row.inputVisible = !row.inputVisible;
      // console.log(222);
      // 非空判断
      if(row.inputValue.trim().length==0) return
      // 实现不刷新添加数据
      row.attr_vals.push(row.inputValue.trim())
     
      this.GetAttrList(row)
       row.inputValue=''
    },

    // 定义一个获取参数的函数
    async GetAttrList(row){
        var attrParams = {
        id:this.catId,
        attrId:row.attr_id,
        attr_name:row.attr_name,
        attr_sel:this.activeName,
        attr_vals:row.attr_vals.join(',')
      }
      // 发送请求添加tag标签
       const {data:res}=await AddAttrList_api(attrParams)
      //  console.log(res);
        this.$message({
          showClose: true,
          message: res.meta.msg,
          type: 'success'
        });  
    }
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 20px;
  margin-left: 10px;
  vertical-align: bottom;

}
</style>
